package com.fas.system.service.impl;

import com.fas.common.utils.Arith;
import com.fas.system.domain.vo.DateStatisticsVo;
import com.fas.system.domain.vo.DeviceStatusNUmVo;
import com.fas.system.domain.vo.Latest7AlarmLinesVo;
import com.fas.system.domain.vo.TodayYHOrderVo;
import com.fas.system.mapper.HomePageMapper;
import com.fas.system.service.IHomePageService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class HomePageServiceImpl implements IHomePageService {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Resource
    private HomePageMapper homePageMapper;

    @Override
    public Latest7AlarmLinesVo getLatest7daysAlarmLines(Integer deptId,Integer cooperationCompanyId) {
        Latest7AlarmLinesVo result = new Latest7AlarmLinesVo();
        // 报警确认（1：真实火警，2：误报，3：测试）
        List<DateStatisticsVo> hjDateNums = homePageMapper.getLatest7daysAlarmLines(deptId,1,cooperationCompanyId);
        List<DateStatisticsVo> hjDateNums_ = getczKptJByDays(hjDateNums);

        List<DateStatisticsVo> wbDateNums = homePageMapper.getLatest7daysAlarmLines(deptId,2,cooperationCompanyId);
        List<DateStatisticsVo> wbDateNums_ = getczKptJByDays(wbDateNums);

        List<DateStatisticsVo> csDateNums = homePageMapper.getLatest7daysAlarmLines(deptId,3,cooperationCompanyId);
        List<DateStatisticsVo> csDateNums_ = getczKptJByDays(csDateNums);

        result.setHjDateNums(hjDateNums_);
        result.setWbDateNums(wbDateNums_);
        result.setCsDateNums(csDateNums_);
        return result;
    }

    @Override
    public DeviceStatusNUmVo getDeviceStatusNum(Integer deptId,Integer cooperationCompanyId) {
        DeviceStatusNUmVo deviceStatusNUmVo = new DeviceStatusNUmVo();
        List<Map<String, Long>> deviceStatusNum = homePageMapper.getDeviceStatusNum(deptId,cooperationCompanyId);
        AtomicInteger totalNum = new AtomicInteger();
        deviceStatusNum.forEach(d ->{
            int count = Integer.parseInt(d.get("count").toString());
            // 设备状态 0正常 1故障 2离线 3报警 为空则是：未启用4")
            switch (Integer.parseInt(String.valueOf(d.get("status")))){
                case 0:
                    deviceStatusNUmVo.setNormalNum(count);
                    break;
                case 1:
                    deviceStatusNUmVo.setFaultNum(count);
                    break;
                case 2:
                    deviceStatusNUmVo.setOfflineNum(count);
                    break;
                case 3:
                    deviceStatusNUmVo.setAlarmNum(count);
                    break;
                case 4:
                    deviceStatusNUmVo.setUnStartNum(count);
                    break;
                default:
                    break;
            }
            totalNum.addAndGet(count);
        });
        deviceStatusNUmVo.setTotalNum(totalNum.intValue());
        int normalNum = deviceStatusNUmVo.getNormalNum();
        if (totalNum.intValue() != 0){
            deviceStatusNUmVo.setIntactRate(String.valueOf(Arith.div(normalNum,totalNum.doubleValue(),2)));
        }
        return deviceStatusNUmVo;
    }

    @Override
    public Map<String,Object> getOverviewDeptNum(Integer deptId,Integer cooperationCompanyId) {
        List<Map<String,Integer>> lst = homePageMapper.getOverviewDeptNum(deptId,cooperationCompanyId);
        Map<String,Object> resultMap = new HashMap<>();
        lst.forEach(map->{
            resultMap.put("buildingNum",map.get("buildingNum"));
            resultMap.put("miniatureFireStationNum",map.get("miniatureFireStationNum"));
            resultMap.put("networkDeptNum",map.get("networkDeptNum"));
        });
        return resultMap;
    }

    @Override
    public TodayYHOrderVo getTodayYHOrderNumRate(Integer deptId,Integer cooperationCompanyId) {
        TodayYHOrderVo todayYHOrderVo = new TodayYHOrderVo();
        int total = homePageMapper.getTodayYHOrderAll(deptId,cooperationCompanyId);
        int unFinished = homePageMapper.getTodayYHOrderUnfinished(deptId,cooperationCompanyId);
        int finished = total-unFinished;
        double unFinishRate_ = Arith.div(unFinished, total, 2);
        if (unFinishRate_ != 0){
            double finishRate_ = 1-unFinishRate_;
            todayYHOrderVo.setFinishRate(String.valueOf(finishRate_));
        }else{
            todayYHOrderVo.setFinishRate("0.0");
        }
        todayYHOrderVo.setUnFinishRate(String.valueOf(unFinishRate_));
        todayYHOrderVo.setFinishNum(finished);
        todayYHOrderVo.setTotal(total);
        todayYHOrderVo.setUnFinishNum(unFinished);
        return todayYHOrderVo;
    }

    public List<DateStatisticsVo> getczKptJByDays(List<DateStatisticsVo> statistics){

        // 不够7天，说明日期存在空缺
        if (statistics.size() < 7) {
            // Step 1:从查询结果中提取日期
            List<LocalDate> resultDateList = new ArrayList<>(statistics.size());
            statistics.forEach(row ->{
                resultDateList.add(row.getDate());
            });
            // Step 2:获取当前时间的前7天时间，共7天
            LocalDate localDate = LocalDate.now(); //获取今天的日期
            LocalDate[] datesArray = {localDate.plusDays(-6), localDate.plusDays(-5), localDate.plusDays(-4),localDate.plusDays(-3),localDate.plusDays(-2),localDate.plusDays(-1),localDate };
            // Step 3:array-->list
            List<LocalDate> addDateList = new ArrayList<>(Arrays.asList(datesArray));
            // Step 4:将查询结果中的日期排除在外
            addDateList.removeAll(resultDateList);
            // Step 5:准备将要填充的数据
            List<DateStatisticsVo> addList = new ArrayList<>(addDateList.size());
            addDateList.forEach(date -> {
                addList.add(new DateStatisticsVo(date,0));
            });
            // Step 6:添加到原有list中
            statistics.addAll(addList);
            // Step 7:冒泡排序
            for (int i = 0; i < statistics.size() - 1; i++) {
                for (int j = 1; j < statistics.size() - i; j++) {
                    DateStatisticsVo statisticsVo;
                    // 前面的日期大于后面的日期
                    if ((statistics.get(j - 1).getDate()).isAfter(statistics.get(j).getDate())) {
                        statisticsVo = statistics.get(j - 1);
                        // 交换值
                        statistics.set((j - 1), statistics.get(j));
                        statistics.set(j, statisticsVo);
                    }
                }
            }
        }
        statistics.forEach(s-> s.setDateStr(dtf.format(s.getDate())));
        return statistics;
    }


}
